package com.zc.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.zc.servicebase.exception.CongException;
import com.zc.utils.R;
import com.zc.vod.service.VodService;
import com.zc.vod.utils.ConstantVod;
import com.zc.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/vodService/video")
@CrossOrigin
public class VodController {

	@Autowired
	private VodService vodService;

	@PostMapping("/uploadVideo")
	public R uploadVideo(MultipartFile file) {
		String videoId = vodService.uploadVideo(file);
		return R.ok().data("videoId", videoId);
	}

	// 根据视频Id删除阿里云中视频
	@DeleteMapping("/deleteVideo/{videoId}")
	public R deleteVideo(@PathVariable("videoId") String videoId) {
		DefaultAcsClient vodClient = InitVodClient.createVodClient(ConstantVod.ACCESS_KEY_ID, ConstantVod.ACCESS_KEY_SECRET);
		DeleteVideoRequest request = new DeleteVideoRequest();

		request.setVideoIds(videoId);

		DeleteVideoResponse response = null;
		try {
			response = vodClient.getAcsResponse(request);
			return R.ok();
		} catch (ClientException e) {
			e.printStackTrace();
			throw new CongException(R.error().getCode(), "删除视频失败");
		}
	}

	// 删除多个视频
	@DeleteMapping("/deleteVideoList")
	public R deleteVideoList(@RequestParam List<String> videoIdList) {
		vodService.removeVideoList(videoIdList);
		return R.ok();
	}

	// 根据视频id获取视频凭证
	@GetMapping("/getPlayAuth/{videoId}")
	public R getPlayAuth(@PathVariable String videoId){
		//获取阿里云存储相关常量
		String accessKeyId = ConstantVod.ACCESS_KEY_ID;
		String accessKeySecret = ConstantVod.ACCESS_KEY_SECRET;

		//初始化
		DefaultAcsClient client = InitVodClient.createVodClient(accessKeyId, accessKeySecret);

		//请求
		GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
		request.setVideoId(videoId);

		//响应
		GetVideoPlayAuthResponse response = null;
		try {
			response = client.getAcsResponse(request);
		} catch (ClientException e) {
			e.printStackTrace();
		}

		//得到播放凭证
		String playAuth = response.getPlayAuth();

		//返回结果
		return R.ok().message("获取凭证成功").data("playAuth", playAuth);
	}

}
